<script setup>
import { userRegisterService, userLoginService } from '@/api/user' // 引入用户接口
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
// 引入用户store
import { useUserStore } from '@/stores/index'
// 引入路由
import { useRouter } from 'vue-router'
// 切换登录注册表单状态
const isRegister = ref(true)
// 准备ruleForm对象
// 用于提交的表单数据对象
const formModel = ref({
  username: '',
  password: '',
  repassword: ''
})
// 防抖函数工厂，返回一个防抖后的函数
function debounce(func, delay = 300) {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, args)
      timer = null
    }, delay)
  }
}
// 验证密码
// 创建防抖版的密码验证函数
const debouncedCheckRepassword = debounce((rule, value, callback) => {
  if (value !== formModel.value.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
})
// 创建表单元素
const form = ref(null)
// 注册表单提交

const registerForm = async () => {
  // validate 对表单整个内容进行验证，返回Promise对象
  await form.value.validate()
  await userRegisterService(formModel.value) // 发送注册请求
  ElMessage.success('注册成功') // 提示注册成功
  isRegister.value = false // 跳转到登录页面
}
// 切换注册登录页面重置
watch(isRegister, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: ''
  }
})
// 登录表单提交
const userStore = useUserStore() // 引入用户store
const router = useRouter() // 引入路由
const loginForm = async () => {
  // validate 对表单整个内容进行验证，返回Promise对象
  await form.value.validate()
  // 发送登录请求
  const res = await userLoginService(formModel.value)
  // 存储token
  userStore.setToken(res.data.token)
  ElMessage.success('登录成功') // 提示登录成功
  // 跳转到首页
  router.push('/')
}
// 验证表单数据规则对象
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^[\S]{6,16}$/,
      message: '密码6-16位 非空字符组合',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^[\S]{6,16}$/,
      message: '密码6-16位 非空字符组合',
      trigger: 'blur'
    },
    { validator: debouncedCheckRepassword, trigger: 'change' }
  ]
}
</script>

<template>
  <!--
   el -row 表示一行 分24份
   el -col 表示一行的列
    :span=12 表示占12份 即一半
    :span=6  表示一行中占6份 25%
    :offset= 3 表示一行中margin-left 份数

    el-form 表单组件
    el-form-item 表单组件的子组件 一行
    el-input 表单输入框

    校验部分：
    1. el-form => :model="ruleForm" 绑定的整个form表单数据对象
      {username: '', password: ''}
    2. el-form => :rules="rules" 绑定的校验规则
    3. 表单元素 => v-model="ruleForm.username" 绑定表单数据对象中的username字段
    4. el-form-item => prop 配置生效的是哪个校验规则 和rules中的字段对应起来
  -->
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="formModel.repassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="registerForm()"
            class="button"
            type="primary"
            auto-insert-space
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" underline="never" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 登录表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-input :prefix-icon="Clock"></el-input>
        </el-form-item> -->
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" underline="never">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="loginForm()"
            class="button"
            type="primary"
            auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" underline="never" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
